﻿const canvas = require("canvas"); //npm install canvas
const echarts = require("echarts"); //npm install echarts
const fs = require('fs'); //node内置模块,直接引入
const path = require('path')
var MongoClient = require('mongodb').MongoClient;
var server_status = require("./websocket")

var config = require('./config.json')
var server_list = require("./server.json")

var db = new MongoClient(config["mongo"]);
var connections = db.connect();

//创建一个canvas实例
let ctx = canvas.createCanvas(600, 400)
//将canvas实例设置为echarts容器
echarts.setCanvasCreator(() => ctx)
//使用canvas实例为容器创建echarts实例
let chart = echarts.init(ctx)
//echarts配置项
setInterval(() => {
    connections.then(async (db) => {
        const dbo = db.db("serverstatus");

        for (var server_id in server_status) {

            let data1 = [];
            let date1 = [];
            //console.log(server_id)
            let server_collection = dbo.collection(server_status[server_id].name);
            let _temp = await server_collection.find({}).toArray()
            //console.log(_temp)
            for (let i = 0; i < _temp.length; i++) {
                //console.log(_temp[i])
                //var date = new Date(_temp[i].time * 1000);
                date1.push(_temp[i].locale);
                data1.push(_temp[i].rx)
            }
            let option = {
                title: {
                    text: 'download speed'
                },
                xAxis: {
                    type: 'category',
                    boundaryGap: false,
                    data: date1
                },
                yAxis: {
                    min: 1,
                    type: "value",
                    axisLabel: {
                        show: true
                    },
                    splitNumber: 15
                },
                series: [{
                    name: 'speed',
                    type: 'bar',
                    data: data1
                }]
            }
            //设置图标实例配置项
            chart.setOption(option);
            //保存图片
            var date_now = new Date()
            const imgPath = path.resolve(__dirname, './public/' + server_id + '.png')
            fs.writeFileSync(imgPath, chart.getDom().toBuffer());
        }

    })
}, 1000 * 60)